/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.servlet.admin;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.dao.PostDAO;
import model.dao.service.PostDAOService;
import model.entities.Post;
import util.Constants;

/**
 *
 * @author Admin
 */
public class PostManagement extends HttpServlet {

    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String action = request.getParameter(Constants.ACTION) + "";
        try {
            switch (action) {
                case "delete":

                    deletePost(request);
                    break;
                case "enable":
                    activePost(request, true);
                    refeshList(request);
                    break;
                case "disable":
                    activePost(request, false);
                    refeshList(request);
                    break;
                case "Search":
                    search(request);
                    break;
                case "viewsearch":
                    viewSearch(request);
                    break;
                case "newpost":
                    newPost(request, response);
                    break;
                case "editpost":
                    editPost(request, response);
                    break;
                default:
                    loadPost(request);
                    break;
            }
        } catch (Exception e) {
            System.err.println("doGet PostManagement error: "+e.toString());
        }
        request.getRequestDispatcher(Constants.URL_ADMIN).forward(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute(Constants.PAGE, "post_management");
        String action = request.getParameter(Constants.ACTION) + "";
        try {
            switch (action) {
                case "change":
                    changeOffset(request);
                    break;
            }
        } catch (Exception e) {
        }
        request.getRequestDispatcher(Constants.URL_ADMIN).forward(request, response);
    }

    private void editPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute(Constants.PAGE, "newpost");
        request.setAttribute(Constants.EDIT_BY,"admin");
        PostDAOService postService = PostDAO.getInstance();
        int postID = 0;
        try {
            postID = Integer.valueOf(request.getParameter("postid"));
            Post postEdit = postService.getPostByID(postID);
            request.setAttribute(Constants.CURRENT_POST,postEdit);
        } catch (Exception e) {
             System.err.println("editPost PostManagement error: "+e.toString());
        }
    }

    private void deletePost(HttpServletRequest request) {
        request.setAttribute(Constants.PAGE, "post_management");
        PostDAOService postService = PostDAO.getInstance();
        try {
            int postID = Integer.parseInt(request.getParameter(Constants.POST_ID));
            if (postService.deletePost(postID)) {
                request.setAttribute(Constants.MSG_RESULT, "Delete success!");
            } else {
                request.setAttribute(Constants.MSG_RESULT, "Delete faile!");
            }
        } catch (Exception e) {
        }
    }

    private void newPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute(Constants.PAGE, "newpost");
        request.setAttribute(Constants.EDIT_BY,"admin");
        request.getRequestDispatcher(Constants.URL_ADMIN).forward(request, response);
    }

    private void activePost(HttpServletRequest request, boolean isActive) {
        request.setAttribute(Constants.PAGE, "post_management");
        PostDAOService postService = PostDAO.getInstance();
        String result = null;
        try {
            int postID = Integer.parseInt(request.getParameter(Constants.POST_ID));
            if (postService.activePost(isActive, postID)) {
                if (isActive) {
                    result = "Active success!";
                } else {
                    result = "Disactive success";
                }
            } else {
                if (isActive) {
                    result = "Active faile!";
                } else {
                    result = "Disactive falie!";
                }
            }
            request.setAttribute(Constants.MSG_RESULT, result);
        } catch (Exception e) {
        }
    }

    private void changeOffset(HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        String offset = request.getParameter(Constants.OFFSET);
        //   String currentPage = request.getParameter(Constants.PAGE);
        //  session.setAttribute(Constants.CURRENT_PAGE, currentPage);
        session.setAttribute(Constants.CURRENT_OFFSET, offset);
        refeshList(request);

    }

    private void refeshList(HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        String keySearch = (String) session.getAttribute(Constants.KEY_SEARCH);
        if (keySearch != null) {
            viewSearch(request);
        } else {
            loadPost(request);
        }
    }

    private void search(HttpServletRequest request) throws Exception {
        request.setAttribute(Constants.PAGE, "post_management");
        PostDAOService postServie = PostDAO.getInstance();
        HttpSession session = request.getSession();
        String searchType = request.getParameter(Constants.TYPE_SEARCH);
        String searchKey = request.getParameter(Constants.KEY_SEARCH);
        session.setAttribute(Constants.KEY_SEARCH, searchKey);
        session.setAttribute(Constants.TYPE_SEARCH, searchType);
        List<Post> listResultSearch = postServie.searchPost(searchType, searchKey);
        setListPerPage(request, listResultSearch);
    }

    private void viewSearch(HttpServletRequest request) throws Exception {
        request.setAttribute(Constants.PAGE, "post_management");
        PostDAOService postServie = PostDAO.getInstance();
        HttpSession session = request.getSession();
        session.setAttribute(Constants.CURRENT_PAGE, request.getParameter(Constants.PAGE));
        String searchType = (String) session.getAttribute(Constants.TYPE_SEARCH);
        String searchKey = (String) session.getAttribute(Constants.KEY_SEARCH);
        List<Post> listResultSearch = postServie.searchPost(searchType, searchKey);
        setListPerPage(request, listResultSearch);
    }

    private void loadPost(HttpServletRequest request) throws Exception {
        request.setAttribute(Constants.PAGE, "post_management");
        HttpSession session = request.getSession();
        session.setAttribute(Constants.CURRENT_PAGE, request.getParameter(Constants.PAGE));
        session.removeAttribute(Constants.KEY_SEARCH);
        session.removeAttribute(Constants.TYPE_SEARCH);
        PostDAOService postServie = PostDAO.getInstance();
        List<Post> listResultSearch = postServie.getListPost();
        setListPerPage(request, listResultSearch);
    }

    private void setListPerPage(HttpServletRequest request, List<Post> listPost) throws Exception {
        int page = 1, offset = 2;
        try {
            HttpSession session = request.getSession();
            String sPage = (String) session.getAttribute(Constants.CURRENT_PAGE);
            if (sPage != null) {
                page = Integer.parseInt(sPage);
            } else {
                session.setAttribute(Constants.CURRENT_PAGE, page);
            }
            String sOffset = (String) session.getAttribute(Constants.CURRENT_OFFSET);
            if (sOffset != null) {
                offset = Integer.valueOf(sOffset);
            }
            request.setAttribute(Constants.CURRENT_OFFSET, offset);
            request.setAttribute(Constants.TOTAL_PAGE, Math.ceil(listPost.size() * 1.0 / offset));
            int recordBegin = (page - 1) * offset;
            int recordEnd = recordBegin + offset - 1;
            List<Post> lisPostPerPage = new ArrayList<>();
            for (int i = 0; i < listPost.size(); i++) {
                if (i >= recordBegin && i <= recordEnd) {
                    lisPostPerPage.add(listPost.get(i));
                }
            }
            request.setAttribute(Constants.LIST_POST, lisPostPerPage);
        } catch (Exception e) {
            //   System.out.println(e.toString());
        }
    }

//    @Override
//    protected void doGet(HttpServletRequest request, HttpServletResponse response)
//            throws ServletException, IOException {
//        response.setContentType("text/html;charset=UTF-8");
//        PrintWriter out = response.getWriter();
//
//        String action = request.getParameter(Constants.ACTION);
//        request.setAttribute(Constants.PAGE, "post_management");
//
//        String p = request.getParameter(Constants.PAGE);
//        if (p != null) {
//            setListPost(request);
//        } else {
//            setList(request);
//            setListPost(request);
//        }
//        request.getRequestDispatcher(Constants.URL_ADMIN).forward(request, response);
//    }
//
//    private void setList(HttpServletRequest request) {
//        int offset = 2;
//        String off = request.getParameter(Constants.OFFSET);
//        if (off != null) {
//            offset = Integer.valueOf(off);
//        }
//
//        PostDAOService postService = PostDAO.getInstance();
//
//        List<Post> listPost = null;
//        HttpSession session = request.getSession();
//        String keySearch = (String) session.getAttribute(Constants.KEY_SEARCH);
//        try {
//            if (keySearch != null) {
//                String typeSearch = (String) session.getAttribute(Constants.TYPE_SEARCH);
//                listPost = postService.searchPost(typeSearch, keySearch, 0, 0);
//            } else {
//                session.removeAttribute(Constants.KEY_SEARCH);
//                session.removeAttribute(Constants.TYPE_SEARCH);
//                listPost = postService.getListPost(0, 0);
//            }
//            request.setAttribute(Constants.CURRENT_PAGE, 1);
//            request.setAttribute(Constants.TOTAL_PAGE, (int) Math.ceil((float) listPost.size() / offset));
//        } catch (Exception e) {
//        }
//        request.getSession().setAttribute(Constants.LIST_POST_TOTAL, listPost);
//    }
//
//    private void setListPost(HttpServletRequest request) throws ServletException, IOException {
//        int offset = 2;
//        int page = 1;
//        try {
//
//            String p = request.getParameter(Constants.PAGE);
//            if (p != null) {
//                page = Integer.valueOf(p);
//            }
//            int recordBegin = (page - 1) * offset;
//            int recordEnd = page * offset - 1;
//
//            List<Post> listPost = (List<Post>) request.getSession().getAttribute(Constants.LIST_POST_TOTAL);
//            //////////////////////////////
//            List<Post> listPostPerPage = new ArrayList<Post>();
//            for (int i = recordBegin; i < listPost.size(); i++) {
//                if (i <= recordEnd) {
//                    listPostPerPage.add(listPost.get(i));
//                }
//            }
//            ///////////////////////////////
//            request.setAttribute(Constants.LIST_POST, listPostPerPage);
//        } catch (Exception e) {
//            System.out.println(e.getMessage());
//        }
//
//    }
//
//    /**
//     * Handles the HTTP <code>POST</code> method.
//     *
//     * @param request servlet request
//     * @param response servlet response
//     * @throws ServletException if a servlet-specific error occurs
//     * @throws IOException if an I/O error occurs
//     */
//    @Override
//    protected void doPost(HttpServletRequest request, HttpServletResponse response)
//            throws ServletException, IOException {
//        response.setContentType("text/html;charset=UTF-8");
//        PrintWriter out = response.getWriter();
//        request.setAttribute(Constants.PAGE, "post_management");
//        String action = request.getParameter(Constants.ACTION);
//        if (action != null) {
//            switch (action) {
//                case "search":
//                    HttpSession session = request.getSession();
//                    session.setAttribute(Constants.TYPE_SEARCH, request.getParameter(Constants.TYPE_SEARCH));
//                    session.setAttribute(Constants.KEY_SEARCH, request.getParameter(Constants.KEY_SEARCH));
//                    setList(request);
//                    setListPost(request);
//                    break;
//            }
//        }
//        request.getRequestDispatcher(Constants.URL_ADMIN).forward(request, response);
//    }
}
